<?php
namespace app\index\controller;

use think\Request;
use think\Db;

use app\index\model\question as QuestionModel;
use app\index\model\user as UserModel;
use app\index\model\questionImage as QuestionImageModel;


class Question 
{
    public function getDataTotal ($keyName, $keyWord)
    {
        $sql = null;
        $queTab = 'dcw_fastask_question';
        $userTab = 'dcw_fastask_user';
        if ($keyName === 'user') {
            $sql = "SELECT COUNT(*) AS dataTotal FROM 
                            (SELECT $queTab.* FROM $queTab, $userTab
                             WHERE $userTab.userName = '$keyWord'
                             AND $queTab.askerToken = $userTab.userToken
                            ) as virtual;
            "; 
        }
        else if ($keyName === '') {
            $sql = "SELECT COUNT(*) AS dataTotal FROM $queTab
            ";
        }
        else {
            $sql = "SELECT COUNT(*) AS dataTotal FROM $queTab
                    WHERE $keyName = '$keyWord'
            ";
        }
        $note = Db::query($sql);
        $dataTotal = $note[0]['dataTotal'];
        return $dataTotal;
    }
    public function getBorderId($dataNum, $page, $keyName, $keyWord)
    {
        //根据页码和数据数目获取应查询数据的第一个 id     
        $boderId = 0;
        if ($page == 1) {
            $queTab = "dcw_fastask_question";
            $sql = "SELECT * FROM $queTab ORDER BY id DESC limit 1";
            $res = Db::query($sql);
            if ($res == NULL) {
                $boderId = 0;
            }
            else {
                $boderId = $res[0]['id'] + 1;
            }
        }
        else {
            $allNotDataId = null;
            $limit = $dataNum * ($page - 1);
            if ($keyName == 'user') {
                $userTab = 'dcw_fastask_user';
                $queTab = 'dcw_fastask_question';
                $sql = "SELECT $queTab.* FROM $userTab, $queTab 
                        WHERE $userTab.userName='$keyWord'
                        AND $queTab.askerToken=$userTab.userToken
                        ORDER BY $queTab.id DESC LIMIT $limit
                ";
                $allNotDataId = Db::query($sql);
            }
            else {
                $query = $keyName == '' ? 
                     function ($query) use ($page, $dataNum) {
                        $query->limit($dataNum * ($page - 1))->order('id', 'desc');
                     }:
                     function ($query) use ($page, $dataNum, $keyName, $keyWord) {
                        $query->where($keyName, $keyWord)->limit($dataNum * ($page - 1))->order('id', 'desc');
                     };
                $allNotDataId = QuestionModel::all($query);
                
            }
            $boderId = $allNotDataId[count($allNotDataId) - 1]['id'];
            
        }
        return $boderId;
    }
    //获取问题的相关信息，用户头像，相关图片
    public function getQuestionInfo ($allNote) 
    {
        
        for ($i = 0; $i < count($allNote); $i ++)
        {
            $value = $allNote[$i];
            //获取用户头像，用户名
            $userToken = $value['askerToken'];
            $user = UserModel::get(['userToken' => $userToken]);
            $userAvatar = $user == NULL ? '无' : $user['userAvatar'];
            $userName = $user == NULL ? '无' : $user['userName'];
            $userInfo = [
                'userAvatar' => $userAvatar,
                'userName' => $userName
            ];
            $allNote[$i]['askerInfo'] = $userInfo;

            //获取相关图片
            $queImage = QuestionImageModel::all(['questionToken' => $value['id']]);
            $questionImage = [];
            foreach ($queImage as $key => $value) {
                $questionImage[] = $value['imgUrl'];
            }
            $allNote[$i]['questionImage'] = $questionImage;
        }


        return $allNote;
        
    }
    public function getQuestion(Request $request)
    {
        //获取请求参数
        $keyName = $request->param('keyName');
        $keyWord = $request->param('keyWord');
        $page = $request->param('page');
        $dataNum = $request->param('dataNum');

        //初始化消息
        $message = '';
        $status = 0;

        //获取边缘 id
        $boderId = $this->getBorderId($dataNum, $page, $keyName, $keyWord);
       
        //获取表中数据总条数
        $dataTotal = $this->getDataTotal($keyName, $keyWord);

        //根据 keyName 设置查询体
        $query = null;
        $allNote = null;
        if ($keyName == '') {
           $query = function ($query) use ($dataNum, $boderId) {
                $query->where('id', '<', $boderId)->order('id', 'desc')->limit($dataNum);
           };
           $allNote = QuestionModel::all($query);
        }
        else if ($keyName == 'user') {
            $userTab = 'dcw_fastask_user';
            $queTab = 'dcw_fastask_question';
            $sql = "SELECT $queTab.* FROM $userTab, $queTab 
                    WHERE $userTab.userName='$keyWord'
                    AND $queTab.askerToken=$userTab.userToken
                    AND $queTab.id < $boderId
                    ORDER BY id DESC LIMIT $dataNum
            ";
            $allNote = Db::query($sql);
        }
        else {
            $query = function ($query) use ($dataNum, $boderId, $keyName, $keyWord) {
                $query->where('id', '<', $boderId)->where($keyName, $keyWord)->order('id', 'desc')->limit($dataNum);
            };
            $allNote = QuestionModel::all($query);
        }

        $allNote = $this->getQuestionInfo($allNote);
        //返回消息
        $data = [
            'allNote' => $allNote,
            'dataTotal' => $dataTotal
        ];
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, $data);
        return $json;

    }

    //修改问题
    public function editQuestion (Request $request)
    {
        //获取请求参数
        $id = $request->param('id');
        $kindName = $request->param('kindName');
        $payPrice = $request->param('payPrice');
        $questionContent = $request->param('questionContent');
        $isAnonymous = $request->param('isAnonymous');
        $isSolved = $request->param('isSolved');
        $isShowPage = $request->param('isShowPage');
        $isShow = $request->param('isShow');
        $isClose = $request->param('isClose');
        $isPublic = $request->param('isPublic');

        //初始化消息
        $message = '';
        $status = 0;

        //更新数据
        $updateQuestion = QuestionModel::get(["id" => $id]);
        if ($updateQuestion == NULL) {
            $message = 'the question is not exist.';
            $status = 2;
        }
        else {
            $updateQuestion->kindName = $kindName;
            $updateQuestion->payPrice = $payPrice;
            $updateQuestion->questionContent = $questionContent;
            $updateQuestion->isAnonymous = $isAnonymous;
            $updateQuestion->isSolved = $isSolved;
            $updateQuestion->isShowPage = $isShowPage;
            $updateQuestion->isShow = $isShow;
            $updateQuestion->isClose = $isClose;
            $updateQuestion->isPublic = $isPublic;
            if ($updateQuestion->save()) {
                $message = 'update question is success.';
                $status = 0;
            }
            else {
                $message = 'update question is fail.';
                $status = 1;
            }
        }
        //返回消息
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;
       
    }

    //删除某个问题以及相关
    public function delQuestion(Request $request)
    {
        //获取请求参数
        $id = $request->param('id');
        
        //初始化信息
        $message = '';
        $status = 0;
        
        $question = QuestionModel::get(["id" => $id]);
        if ($question->delete()) {
            $message = 'delete question success.';
            $status = 0;
        }
        else {
            $message = 'delete question success.';
            $status = 1;
        }

        //返回消息
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;

    }
    
}